package com.ruoyi.warning.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.warning.domain.entity.DevicesType;
import com.ruoyi.warning.domain.vo.DeviceTypeVO;
import com.ruoyi.warning.mapper.DevicesTypeMapper;
import com.ruoyi.warning.service.IDevicesTypeService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenhc
 * @since 2025-08-06
 */
@Service
public class DevicesTypeServiceImpl extends ServiceImpl<DevicesTypeMapper, DevicesType> implements IDevicesTypeService {

    @Override
    public Object tree() {
        List<DevicesType> list = this.list();
        Map<Integer, DeviceTypeVO> nodeMap = new HashMap<>();
        if(list == null || list.isEmpty()){
            return null;
        }

        for(DevicesType item : list){
            DeviceTypeVO vo = new DeviceTypeVO();
            BeanUtils.copyProperties(item, vo);
            nodeMap.put(item.getTypeId(), vo);
        }
        List<DeviceTypeVO> rootNodes = new ArrayList<>();
        for (DeviceTypeVO node : nodeMap.values()) {
            Integer parentId = node.getParentId();
            if (parentId == 0 || !nodeMap.containsKey(parentId)) {
                // 根节点
                rootNodes.add(node);
            } else {
                // 非根节点，添加到父节点的子节点列表中
                DeviceTypeVO parentNode = nodeMap.get(parentId);
                // 检查子节点列表是否为 null，如果为 null 则初始化
                if (parentNode.getChild() == null) {
                    parentNode.setChild(new ArrayList<>());
                }
                parentNode.getChild().add(node);
            }
        }
        return rootNodes;
    }
}
